#include "baiduface.h"
#include <QNetworkReply>
#include <QUrlQuery>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include "widget.h"

baiduFace::baiduFace(const QString& appkey, const QString& secret, QObject *parent)
    : QObject(parent), _appkey(appkey), _secret(secret)
{
    _client = new QNetworkAccessManager(this);
    getToken();
}

//获取access_token的值
void baiduFace::getToken()
{
    QUrlQuery params;
    params.addQueryItem("grant_type", "client_credentials");
    params.addQueryItem("client_id", _appkey);
    params.addQueryItem("client_secret", _secret);
    QNetworkRequest request(QUrl("https://aip.baidubce.com/oauth/2.0/token"));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
    _client->post(request, params.toString(QUrl::FullyEncoded).toUtf8());
    connect(_client, &QNetworkAccessManager::finished, this, &baiduFace::on_tokenReply);
}

//解析返回access_token的json字符串
void baiduFace::on_tokenReply(QNetworkReply* reply)
{
    QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();
    _token = json["access_token"].toString();
    disconnect(_client, &QNetworkAccessManager::finished, this, &baiduFace::on_tokenReply);
    reply->deleteLater();
}

//在百度云端进行连接后，对于人脸进行识别并得到其返回消息
void baiduFace::search(const QByteArray face, const QString groups)
{
    _uid.clear();

    QUrlQuery params;
    params.addQueryItem("access_token", _token);
    QUrl api("https://aip.baidubce.com/rest/2.0/face/v3/search");
    api.setQuery(params);

    QJsonObject body;
    body["image"] = QString(face.toBase64());//图片信息
    body["image_type"] = "BASE64";//编码格式
    body["group_id_list"] = groups;//搜索的组的id
    QJsonDocument data(body);

    QNetworkRequest request(api);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    connect(_client, &QNetworkAccessManager::finished, this, &baiduFace::on_searchReply);
    _client->post(request, data.toJson());
}

//解析返回出来的字符串，判断是否识别成功并记录错误信息以及用户账号
void baiduFace::on_searchReply(QNetworkReply* reply)
{
    disconnect(_client, &QNetworkAccessManager::finished, this, &baiduFace::on_searchReply);
    QJsonObject json = QJsonDocument::fromJson(reply->readAll()).object();

    //如果搜索失败，则返回的json字符串中error_code != 0，且会有错误信息提示
    _error_code = json["error_code"].toInt();
    if (_error_code)
    {
        emit isfound(false);
        _error_mesg = json["error_msg"].toString();
        qDebug()<<_error_mesg;
    }
    else
    {
        //在人脸库中找到了对应人脸，则解析json字符串，找到该用户的有效信息（工号）
        QJsonObject result = json["result"].toObject();
        QJsonArray user_list = result["user_list"].toArray();
        for (int i = 0; i < user_list.size(); i++)
        {
            QJsonObject user = user_list[i].toObject();
            _uid = user["user_id"].toString();
            emit isfound(true);
        }
    }
    reply->deleteLater();
}

QString baiduFace::userid()
{
    //返回工号，以便去做数据库以及显示操作
    qDebug()<<_uid;
    return _uid;
}
